﻿using UnityEngine;
using System.Collections.Generic;
using com.guojin.core.io;
using com.guojin.core.io.message;
using com.guojin.mj.net.message;

public class SocketMgr : MonoBehaviour, WebSocketUnityDelegate {

    private MessageFactoryImpi msgFactory = MessageFactoryImpi.instance;
    public WebSocketUnity webSocket;

    public bool isNetOpen { get;   set; } //open为true， 断开为false

    private static SocketMgr instance = null;
    public static SocketMgr GetInstance()
    {
        return SocketMgr.instance;
    }
    void Awake() {
            SocketMgr.instance = this;
            DontDestroyOnLoad(this);
        }

    public void InitNet() {
            Debug.Log("[SocketMgr] 服务器连接地址: " + URLConst.ServerAdress);
            webSocket = new WebSocketUnity(URLConst.ServerAdress, this);
            webSocket.Open();        
    }

    public void CloseSocket()
    {
        webSocket.Close();
    }

    public void Send(byte[] data) {
        if (data != null) {
            this.webSocket.Send(data);
        }
    }

    //  websocket is opened 的时候执行
    public void OnWebSocketUnityOpen(string sender)
    {
        SetIsNetOpen(true);
        SocketMessageQueue.open = false;
        Debug.Log("[NetSocketMgr] WebSocket connected, " + sender);
    }

    public void OnWebScoketclose()
    {
        SetIsNetOpen(false);
        webSocket.Close();
    }


    public void OnWebSocketUnityOnMessage(string sender) {
        Debug.Log("[NetSocketMgr] OnWebSocketUnityOnMessage");
    }

    // websocket is closed 的时候执行
    public void OnWebSocketUnityClose(string reason) {
        Debug.Log("WebSocket Close : " + reason);
        SetIsNetOpen(false);
    }

    // websocket接收到 string 类型的message是执行
    public void OnWebSocketUnityReceiveMessage(string message) {
        Debug.Log("Received from server : " + message);
    }

    public void OnWebSocketUnityReceiveDataOnMobile(string base64EncodedData) {
        byte[] decodedData = webSocket.decodeBase64String(base64EncodedData);
        OnWebSocketUnityReceiveData(decodedData);
    }

    private void Update() {
        SocketMessageQueue.GetInstance().UpdateQueue();
    }

    // This event happens when the websocket did receive data
    public void OnWebSocketUnityReceiveData(byte[] data) {
        Byte readBuffer = new Byte(new List<byte>(data));
        readBuffer.endian = Byte.BIG_ENDIAN;
        readBuffer.pos = 0;
        MarkCompressInput in0 = MarkCompressInput.create(readBuffer);
        int type = in0.readInt();
        int id = in0.readInt();
        if (id == 24 || (id == 35))
        {
            return;
        }
        Message msg = msgFactory.getMessage(type, id);       
        if (GameData.GetInstance().CanAddMessage && id != 15 )                       //7，15是心跳包
        {
            GameData.GetInstance().messagelist.Add(msg);
        }
        if (!(type == 7 && id == 15))
        {
            Debug.Log("[NetSocketMgr]addNetMsg: type:" + type + ",id: " + id);
        }

        msg.decode(in0);
        SocketMessageQueue.GetInstance().addMsg(msg);   //添加消息
    }

    public void OnWebSocketUnityError(string error) {
        Debug.Log("[NetSocketMgr] socket error");
        SetIsNetOpen(false);
    }

    public void SetIsNetOpen(bool isOpen)
    {
        if (isOpen)
        {
            isNetOpen = true;
        }
        else
        {
            //isNetOpen = false;
        }
    }
}
